<template>
  <div class="msg">
  </div>
</template>

<script>
  export default {
    name: 'Home',
    data() {
      return {
        WEB_SOCKET_URL: "ws://127.0.0.1:9999/connection",
        webSocket: null,
        userId: "12"
      }
    },
    created() {
      this.initWebSocket()
    },
    destroyed() {

    },
    methods: {
      initWebSocket() {
        const url = this.WEB_SOCKET_URL + "/" + this.userId;
        if (typeof (WebSocket) == "undefined") {
          console.log("您的浏览器不支持WebSocket");
        } else {
          console.log("您的浏览器支持WebSocket");
          // 实现化 WebSocket 对象，指定要连接的服务器地址与端口  建立连接
          console.log(url);
          if (this.webSocket != null) {
            this.webSocket.close();
            this.webSocket = null;
          }
          this.webSocket = new WebSocket(url);
          //打开事件
          this.webSocket.onopen = function () {
            console.log("websocket已打开");
          };
          //获得消息事件
          this.webSocket.onmessage = function (msg) {
            console.log(msg.data);
          };
          //关闭事件
          this.webSocket.onclose = function () {
            console.log("websocket已关闭");
          };
          //发生了错误事件
          this.webSocket.onerror = function () {
            console.log("websocket发生了错误");
          }
        }
      }
    }
  }
</script>
